package demo.util;

import com.betfair.www.publicapi.types.exchange.v5.Market;
import com.betfair.www.publicapi.types.exchange.v5.Runner;
import org.apache.commons.lang.StringUtils;

/**
 * Created with IntelliJ IDEA.
 * User: markwilliams
 * Date: 8/19/13
 * Time: 10:21 PM
 * To change this template use File | Settings | File Templates.
 */
public class CorrectScore {
    public static int getTotalGoals(Runner r) {
        if (getHomeGoals(r) + getAwayGoals(r) >= 0) {
            return getHomeGoals(r) + getAwayGoals(r);
        } else {
            return Integer.MAX_VALUE;
        }
    }

    public static int getHomeGoals(Runner r) {
        if (!r.getName().trim().equals(Constants.ANY_UNQUOTED)) {
            String[] score = StringUtils.split(r.getName(), "-");
            return parseGoalsFromScoreFragment(score[0]);
        }
        return 0;
    }

    public static int getAwayGoals(Runner r) {
        if (!r.getName().trim().equals(Constants.ANY_UNQUOTED)) {
            String[] score = StringUtils.split(r.getName(), "-");
            return parseGoalsFromScoreFragment(score[1]);
        }
        return 0;
    }

    private static int parseGoalsFromScoreFragment(String s) {
        try {
            return Integer.valueOf(s.trim());
        } catch (NumberFormatException e) {
            return Integer.MAX_VALUE;
        } catch (ArrayIndexOutOfBoundsException e) {
            return Integer.MAX_VALUE;
        }
    }

    public static String findCorrectScoreFromMarketOdds(InflatedMarketPrices prices, Market m) {
        String correctScore = "";
        int minGoalsSoFar = Integer.MAX_VALUE;
        for (InflatedMarketPrices.InflatedRunner r : prices.getRunners()) {
            Runner marketRunner = null;

            for (Runner mr : m.getRunners().getRunner()) {
                if (mr.getSelectionId() == r.getSelectionId()) {
                    marketRunner = mr;
                    break;
                }
            }

            if (r.getLayPrices().size() != 0 && !marketRunner.getName().trim().equals(Constants.ANY_UNQUOTED)) {
                if (minGoalsSoFar > CorrectScore.getTotalGoals(marketRunner)) {
                    minGoalsSoFar = CorrectScore.getTotalGoals(marketRunner);
                    correctScore = marketRunner.getName();
                    System.out.println("Found Runner with possible odds " + marketRunner.getName());
                }
                //System.out.println("Found Runner with possible odds " + marketRunner.getName());
            }
        }
        return correctScore;
    }

    public static int getTotalGoalsInMarket(InflatedMarketPrices prices, Market market) {
        String[] score = StringUtils.split(findCorrectScoreFromMarketOdds(prices, market), "-");
        int goals = 0;

        goals += parseGoalsFromScoreFragment(score[0]);
        goals += parseGoalsFromScoreFragment(score[1]);

        findCorrectScoreFromMarketOdds(prices, market);

        return goals;
    }
}